const cloud = require('wx-server-sdk')
// 初始化 cloud
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const MAX_LIMIT = 10
const wxContext = cloud.getWXContext()
exports.main = async (event, context) => {

  // 先取出集合记录总数
  const countResult = await db.collection('clock_in').where({ _openid: cloud.getWXContext().OPENID}).count()
  const total = countResult.total
  // 计算需分几次取
  // const batchTimes = Math.ceil(total / 20)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  // for (let i = 0; i < batchTimes; i++) {
    const promise = await db.collection('clock_in').where({ _openid: cloud.getWXContext().OPENID }).skip(event.pageNum * MAX_LIMIT).limit(MAX_LIMIT).orderBy('time', 'desc').get()
    // tasks.push(promise)
  // }
  return {
    data: promise.data,
    total: total
  }
  // 等待所有
  // return (await Promise.all(tasks)).reduce((acc, cur) => {
  //   return {
  //     data: acc.data.concat(cur.data),
  //     errMsg: acc.errMsg
  //   }
  // })
}